package com.geline.mybatisplus.interceptor.inner;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.geline.mybatisplus.annotation.AfterDelete;
import com.geline.mybatisplus.annotation.AfterInsert;
import com.geline.mybatisplus.annotation.AfterUpdate;
import com.geline.cloud.util.DynamicSqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;

/**
 * 后置拦截器
 * @AfterInsert  @AfterUpdate  @AfterDelete
 *
 * @author: mx
 * @date: 2024-09-06 16:51
 */
@Slf4j
public class AfterEntityInterceptor implements InnerInterceptor {

    private JdbcTemplate jdbcTemplate;

    public AfterEntityInterceptor(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        SqlCommandType sct = ms.getSqlCommandType();
        if (sct == SqlCommandType.INSERT) {
            this.handleEntity(sct, parameter);
        }else if (sct == SqlCommandType.UPDATE) {
            Object object = parameter;
            if(parameter instanceof MapperMethod.ParamMap){
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                if(map.containsKey("et")){
                    object = map.get("et");
                }
            }
            this.handleEntity(sct, object);
        }else if (sct == SqlCommandType.DELETE) {
            if(ms.getId().contains("deleteById")){
                //com.geline.cloud.system.mapper.SysNoticeMapper
                String mapper = ms.getId().replace(".deleteById", "");
                Class<BaseMapper> mapperClass = ClassUtil.loadClass(mapper);
                BaseMapper baseMapper = SpringUtil.getBean(mapperClass);
                Object entity = baseMapper.selectById((Serializable) parameter);
                this.handleEntity(sct, entity);
            } else if(ms.getId().contains("deleteBatchIds")){
                String mapper = ms.getId().replace(".deleteBatchIds", "");
                Class<BaseMapper> mapperClass = ClassUtil.loadClass(mapper);
                BaseMapper baseMapper = SpringUtil.getBean(mapperClass);

                Object object = parameter;
                if(parameter instanceof MapperMethod.ParamMap){
                    MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                    if(map.containsKey("et")){
                        object = map.get("et");
                    }else if(map.containsKey("param1")){
                        object = map.get("param1");
                    }
                }
                Collection list = (Collection)object;
                for(Object id : list){
                    Object entity = baseMapper.selectById((Serializable) id);
                    this.handleEntity(sct, entity);
                }
            }
        }
    }

    protected void handleEntity(SqlCommandType sct, Object entity){
        if (sct == SqlCommandType.INSERT) {
            AfterInsert[] annArray = entity.getClass().getAnnotationsByType(AfterInsert.class);
            if(annArray != null && annArray.length > 0) {
                for (AfterInsert annotation : annArray) {
                    this.handleInsert(annotation, entity);
                }
            }
        }else if (sct == SqlCommandType.UPDATE) {
            AfterUpdate[] annArray = entity.getClass().getAnnotationsByType(AfterUpdate.class);
            if(annArray != null && annArray.length > 0) {
                for (AfterUpdate annotation : annArray) {
                    this.handleUpdate(annotation, entity);
                }
            }
        }else if (sct == SqlCommandType.DELETE) {
            AfterDelete[] annArray = entity.getClass().getAnnotationsByType(AfterDelete.class);
            if(annArray != null && annArray.length > 0) {
                for (AfterDelete annotation : annArray) {
                    this.handleDelete(annotation, entity);
                }
            }
        }
    }

    protected void handleInsert(AfterInsert annotation, Object entity){
        String value = annotation.value();
        if(StrUtil.isNotBlank(value)){
            String sql = DynamicSqlUtil.parseSQL(value, BeanMap.create(entity));
            if(sql.contains("#{") || sql.contains("${")){
                log.warn("handleInsert can not run sql = {}", sql);
                log.warn("handleInsert entity = {}", BeanMap.create(entity));
            }else {
                jdbcTemplate.update(sql);
                log.info("handleInsert = {}", sql);
            }
        }
    }

    protected void handleUpdate(AfterUpdate annotation, Object entity){
        String value = annotation.value();
        if(StrUtil.isNotBlank(value)){
            String sql = DynamicSqlUtil.parseSQL(value, BeanMap.create(entity));
            if(sql.contains("#{") || sql.contains("${")){
                log.warn("handleUpdate can not run sql = {}", sql);
                log.warn("handleUpdate entity = {}", BeanMap.create(entity));
            }else {
                jdbcTemplate.update(sql);
                log.info("handleUpdate = {}", sql);
            }
        }
    }

    protected void handleDelete(AfterDelete annotation, Object entity){
        String value = annotation.value();
        if(StrUtil.isNotBlank(value)){
            String sql = DynamicSqlUtil.parseSQL(value, BeanMap.create(entity));
            if(sql.contains("#{") || sql.contains("${")){
                log.warn("handleDelete can not run sql = {}", sql);
                log.warn("handleDelete entity = {}", BeanMap.create(entity));
            }else {
                jdbcTemplate.update(sql);
                log.info("handleDelete = {}", sql);
            }
        }
    }
}
